package com.woniuxy.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.entity.AllUser;
import com.woniuxy.core.service.AllUserService;
import com.woniuxy.core.mapper.AllUserMapper;
import com.woniuxy.entity.AllUser;
import com.woniuxy.entity.UserCoupon;
import com.woniuxy.enums.ResponseEnum;
import com.woniuxy.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author nanqiao
 * @description 针对表【all_user(用户基础信息表)】的数据库操作Service实现
 * @createDate 2025-07-11 11:37:57
 */
@Service
public class AllUserServiceImpl extends ServiceImpl<AllUserMapper, AllUser>
        implements AllUserService {

    @Autowired
    private AllUserMapper allUserMapper;

    @Override
    public AllUser getUserById(Long userId) {
        return allUserMapper.getUserById(userId);
    }

    /**
     * 获取优惠券
     *
     * @param couponId
     * @return UserCoupon
     */
    @Override
    public UserCoupon getCoupon(Integer couponId) {
        return allUserMapper.getCoupon(couponId);
    }

    /**
     * 锁定优惠券
     *
     * @param id
     * @return Integer
     */
    @Override
    public Integer lockCoupon(Integer id) {
        return allUserMapper.lockCoupon(id);
    }

    /**
     * 扣除余额
     *
     * @param userId
     * @param amount
     * @return ResponseData
     */
    @Override
    public ResponseData deductBalance(Long userId, BigDecimal amount) {
        // 1. 参数校验
        if (userId == null || amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseData.fail(ResponseEnum.PARAM_ERROR);
        }

        // 2. 查询用户
        AllUser user = allUserMapper.getUserById(Long.valueOf(userId));
        if (user == null) {
            return ResponseData.fail(ResponseEnum.USER_NOT_FOUND);
        }

        // 3. 检查余额是否充足
        if (user.getBalance().compareTo(amount) < 0) {
            return ResponseData.fail(ResponseEnum.INSUFFICIENT_BALANCE);
        }

        // 4. 扣减余额（建议使用数据库乐观锁）

        int rows = allUserMapper.deductBalance(userId, amount);

        if (rows == 0) {
            // 乐观锁冲突，余额已被其他操作修改
            return ResponseData.fail(ResponseEnum.CONCURRENCY_CONFLICT);
        }

        return ResponseData.ok();
    }

    @Override
    public ResponseData increaseBalance(Long sellerId, BigDecimal amount) {
        return ResponseData.ok(allUserMapper.increaseBalance(sellerId, amount));
    }

    @Override
    public List<Long> listRandomUserIds(int limit) {
        return allUserMapper.listRandomUserIds(limit);
    }
}




